<?php

namespace Admin\Controller;

use Common\Lib\Relation;

class BbsController extends CommonController
{
    // 列表
    public function lists()
    {
        $p        = I('get.p', 1);
        $key      = I('param.key');
        $key_type = I('param.key_type');
        $audit    = I('param.audit', '');
        $order    = 'replytime desc';

        $bbs = D('Bbs');

        $map = array();
        $map = array_merge($map, $bbs->map_keywords($key, $key_type));
        if ($audit !== '') {
            $map['audit'] = $audit;
        }

        $lists = $bbs->get_list($map, $p, $order, 10);

        $list = $lists['list'];
        $list = Relation::belongsTo($list, 'User', 'uid', 'uid', 'adduser', array(D('User'), 'auto_user_fill'));
        $list = Relation::hasMany($list, 'BbsTag', 'id', 'bid', 'tags', function ($item){
            foreach ($item as $key => $val) {
                $item[$key] = D('BbsTag')->fill($val);
            }
            return $item;
        });
        $list = Relation::hasMany($list, 'BbsImg', 'id', 'bid', 'imgs', function($item){
            // 获取图片url
            foreach ($item as $key => $val) {
                $imgid = $val['img'];
                $item[$key]['url'] = uploadimgurl($imgid);
            }
            return $item;
        });

        $lists['list'] = $list;

        $this->assign('lists', $lists);

        $this->display();
    }

    // 审核
    public function audit()
    {
        $ids   = I('post.id', '', 'trim');
        $audit = I('post.audit', '', 'intval');

        $ids = is_array($ids) ? implode(',', $ids) : $ids;
        if ($ids && is_match_ids($ids)) {
            $count = D('Bbs')->bbs_audit($audit, $ids);
//            event('bbs_audit', compact('ids', 'state'));
            $this->success("设置成功！");
        } else {
            $this->error('请选择项目！');
        }
    }

    // 删除
    public function delete()
    {
        $ids = I('param.id');
        $ids = is_array($ids) ? implode(",", $ids) : $ids;
        if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/", $ids)) {
            D("Bbs")->del_bbs($ids);

            $this->success("成功删除");
        } else {
            $this->error('请选择要删除的信息！');
        }
    }

    // 附件列表
    public function annex()
    {
        $lists = D("BbsImg")->get_list('', true, '', 12);

        $this->assign('lists', $lists);

        $this->display();
    }

    public function annex_del()
    {
        $ids = I('request.id');
        if (!empty($ids)) {
            $ids = is_array($ids) ? implode(',', $ids) : $ids;
            $map['id'] = array('in', $ids);
            $s   = D("BbsImg")->where($map)->delete();
            $this->success("成功删除{$s}条数据");
        } else {
            $this->error('请选择要删除的信息！');
        }
    }
}